//
//  BanBu_TestHostSpeed.m
//  BanBu
//
//  Created by banbu3 on 10/30/13.
//
//

#import "BanBu_TestHostSpeed.h"
#import "ASIHTTPRequest.h"
#import "BanBuAPIs.h"
#import "AppDataManager.h"
#define FastestTime @"fastesttime"
#define FastestHost @"fastesthost"
@implementation BanBu_TestHostSpeed
-(id)initWithHostList:(NSMutableArray *)arr
{
    self = [super init];
    if(self)
    {
        NSMutableArray *list = [[NSMutableArray alloc] initWithArray:arr];
        self.hostList = list;
        [list release];
        NSMutableDictionary *fast = [[NSMutableDictionary alloc] initWithCapacity:0];
        self.fastHost = fast;
        [fast release];
    }
    return self;
} 
-(void)readyTestHostSpeed
{
    
    int i = 1;
    for(NSString *host in _hostList)
    {
        char str[20] = "com.host.test";
        char s[2];
        sprintf(s, "%d",i);
        strcat(str, s);
        dispatch_queue_t queue = dispatch_queue_create(str, DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            NSString *urlString = [NSString stringWithFormat:@"http://%@/serverping.php",host];
            [self startTest:urlString];
        });
//        free(str);serverping.php
        i++;
    }
}
-(void)startTest:(NSString *)_url
{
    NSDateFormatter *fo = [[NSDateFormatter alloc] init];
    [fo setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS"];
    NSDate *startDate = [NSDate date];
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:_url]];
    [request startSynchronous];
    NSDate *endDate = [NSDate date];

    NSTimeInterval timePass = [endDate timeIntervalSinceDate:startDate];
    if(timePass<[[self.fastHost valueForKey:@"time"] doubleValue]||[[self.fastHost allKeys] indexOfObject:@"time"]==NSNotFound)
    {
        [self.fastHost setValue:[NSNumber numberWithDouble:timePass] forKey:@"time"];
        [self.fastHost setValue:_url forKey:@"url"];
    }
    if(timePass<0.02)
    {
        [self setFastestHost:_url];
    }

    [self setFastestHost:[self.fastHost valueForKey:@"url"]];
    [fo release];
    

}
-(void)setFastestHost:(NSString *)_host
{
    NSString *host = [_host stringByReplacingOccurrencesOfString:@"/serverping.php" withString:@""];
    MyAppDataManager.banbuHostIP = host;
//    MyAppDataManager.banbuHostIP = @"http://koochat.duapp.com";
//    MyAppDataManager.banbuHostIP = @"http://192.168.1.10";
//    MyAppDataManager.banbuHostIP = @"http://74.117.60.99";
}

@end
